﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class Login : PhoneApplicationPage
    {
        private static string key = "user";
        private static string idkey = "id";

        //valori del login presi dal form
        private string user = "";
        private string psw = "";

        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        public Login()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (appSettings.Contains("username"))//arrivo dalla pagina crea account
            {
                userBox.Text = appSettings["username"].ToString();
                appSettings.Remove("username");
            }

            if (NavigationService.CanGoBack)//vengo dalla main page
            {
                NavigationService.RemoveBackEntry();
            }
        }

        private void buttonAccedi_Tap(object sender, GestureEventArgs e)
        {
            //raccolgo dalla pagina
            user = userBox.Text;
            psw = pswBox.Password;

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                //faccio request PHP al DB
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/login.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&user=" + user.ToString() + "&psw=" + psw.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }//GetRequestStreamCallback

        private void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingLogin(result));
            }
        }//GetResponsetStreamCallback

        private void ParsingLogin(string result)
        {
            if (result == "")//query vuota
                MessageBox.Show("incorrect username or password");
            else
            {
                string[] ris = majorSplit(result);

                if (ris[0] == "ERRORE")
                {
                    MessageBox.Show(ris[1]);
                }
                else //se login effettuato
                {
                    string[] dati = minorSplit(ris[0]);
                    int id = Convert.ToInt32(dati[0]);
                    string username = dati[1];
                    string imageURL = dati[2];
                    int points = Convert.ToInt32(dati[3]);
                    int level = Convert.ToInt32(dati[4]);
                    Utente user = new Utente(id,username,imageURL,points,level);

                    //aggiungo i dati in locale
                    appSettings.Add(idkey, id);
                    appSettings.Add(key, user);
                    DataSaver<Utente> myUserDataSaver = new DataSaver<Utente>();
                    myUserDataSaver.SaveMyData(user, "UserObject");

                    //torno indietro alla main page
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));//cambio della pagina
                }
            }
        }

        private void buttonCreaAccount_Tap(object sender, GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreateAccount.xaml", UriKind.Relative));//cambio della pagina
        }

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}